package com.phgame.newsmth.pploader;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import com.phgame.newsmth.R;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class pploader {
	
	Context mContext ;
	MemCache mMemCache ;
	public pploader(Context ctx){
		mContext = ctx;
		mMemCache = new MemCache();
	}
	private boolean isStringHttp(String url){
		if(url.startsWith("http://") || url.startsWith("https://") ){
			return true;
		}else
			return false;
	}
	
	class downloadTask extends AsyncTask<String,Void,Bitmap>{
		ImageView view;
		OutputStream outstream = new ByteArrayOutputStream();
		public downloadTask(ImageView v){
			view = v;
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			String url = params[0];

			Downloader.downloadUrlToStream(url, outstream);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = false;
			options.inSampleSize = 4;
			Bitmap map = BitmapFactory.decodeByteArray(((ByteArrayOutputStream) outstream).toByteArray(), 
					0, ((ByteArrayOutputStream) outstream).toByteArray().length,options);
			
			mMemCache.addCache(url, map);
			return map;
		}
		@Override
		protected void onPostExecute(Bitmap result) {
			BitmapDrawable drawable = new BitmapDrawable(mContext.getResources(),result);
			view.setImageDrawable(drawable);
			view.invalidate();
			super.onPostExecute(result);
		}
		
	
	}
	public int loadImage(String url,ImageView view){
		//first no memcache or diskcache 
		//only download from network
		Log.d("~~~~~~~~","loadImage ~~~~~~~~~getimage~~~~");
		if(url == null || !isStringHttp(url) ){
			return -1;
		}
		//first get from memcache
		if(mMemCache.getDrawble(url) != null){
			Log.d("~~~~~~","loadImage get hit");
			
			view.setImageDrawable(new BitmapDrawable(mContext.getResources(),mMemCache.getDrawble(url)));
			view.invalidate();
		}else{
			Bitmap defaultbitmap = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.ic_launcher);
			Log.d("~~~~~~","defaultbitmap =" + defaultbitmap);
			mMemCache.addCache(url, defaultbitmap);
			new downloadTask(view).execute(url);
		}
		//view.postInvalidate();
		return 0;
	}
}
